package com.coursehub.user.config;

import com.coursehub.user.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT认证拦截器
 */
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"未提供认证token\",\"data\":null}");
            return false;
        }
        
        // 提取token
        String token = authHeader.substring(7);
        
        try {
            // 验证token
            if (!jwtUtil.validateToken(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"message\":\"token无效或已过期\",\"data\":null}");
                return false;
            }
            
            // 将用户信息存储到request中
            String userId = jwtUtil.getUserIdFromToken(token);
            String userAccount = jwtUtil.getUserAccountFromToken(token);
            String userName = jwtUtil.getUserNameFromToken(token);
            
            request.setAttribute("userId", userId);
            request.setAttribute("userAccount", userAccount);
            request.setAttribute("userName", userName);
            
            return true;
            
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token解析失败\",\"data\":null}");
            return false;
        }
    }
}